//
//  XMLAppDelegate.m
//  eBaySearch
//
//  Created by Dang Duc Nam (namk42c@yahoo.com) on 4/29/09.
//  Copyright 2009 Unitech. All rights reserved.
//

#import "XMLAppDelegate.h"
#import "RootViewController.h"

@implementation XMLAppDelegate

@synthesize window;
@synthesize navigationController, list;

- (void)init {
	#define APP_ID @"Unitech04-18ea-430f-bedf-fc47c1b20bd"
	//#define APP_ID nil

	[super init];
}

- (void)applicationDidFinishLaunching:(UIApplication *)application {
	if (APP_ID==nil) {
		NSString *msgAlert = @"Error: You have to define your eBay Application ID in init method of XMLAppDelegate";
		UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:msgAlert delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"OK" otherButtonTitles:nil];
		actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
		[actionSheet showInView:[navigationController view]];
		[actionSheet release];
	}
	// Configure and show the window
	[window addSubview:[navigationController view]];
	[window makeKeyAndVisible];
}

- (id)objectInListAtIndex:(NSUInteger)theIndex {
	return [list objectAtIndex:theIndex];
}
- (void)FindItems:(NSString *)keywords {
	[NSThread detachNewThreadSelector:@selector(search:) toTarget:self withObject:keywords];
}
- (void)search:(NSString *)keywords {
	
	NSAutoreleasePool *pool = [(NSAutoreleasePool*)[NSAutoreleasePool alloc] init];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	NSString *soapMessage = [NSString stringWithFormat:
							 @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
							 "<FindItemsRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\">\n"
							 "<QueryKeywords>%@</QueryKeywords>\n"
							 "<MaxEntries>5</MaxEntries>"
							 "</FindItemsRequest>", keywords
							 ];	
	//NSLog(soapMessage);
	NSURL *url = [NSURL URLWithString:@"http://open.api.ebay.com/shopping?"];
	
	NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
	NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
	
	[theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
	[theRequest addValue: @"http://open.api.ebay.com/shopping?" forHTTPHeaderField:@"SOAPAction"];
	[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
	[theRequest addValue: @"FindItems" forHTTPHeaderField:@"X-EBAY-API-CALL-NAME"];
	[theRequest addValue: @"0" forHTTPHeaderField:@"X-EBAY-API-SITEID"];
	[theRequest addValue: @"571" forHTTPHeaderField:@"X-EBAY-API-COMPATIBILITY-LEVEL"];
	[theRequest addValue: @"XML" forHTTPHeaderField:@"X-EBAY-API-REQUEST-ENCODING"];
	[theRequest addValue: @"XML" forHTTPHeaderField:@"X-EBAY-API-RESPONSE-ENCODING"];
	[theRequest addValue: APP_ID forHTTPHeaderField:@"X-EBAY-API-APP-NAME"];
	[theRequest addValue: @"571" forHTTPHeaderField:@"X-EBAY-API-VERSION"];
	
	[theRequest setHTTPMethod:@"POST"];
	[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
	NSError *error;
	NSURLResponse * response;
	NSData *webData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];	
	
	//NSLog(@"%@", [[[NSString alloc] initWithData:webData encoding:NSASCIIStringEncoding] autorelease]);	
	//NSLog(@"Data Loaded");
	NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:webData];
	
	//Initialize the delegate.
	XMLParser *parser = [[XMLParser alloc] initXMLParser];
	
	//Set delegate
	[xmlParser setDelegate:parser];
	
	//Start parsing the XML file.
	BOOL success = [xmlParser parse];

	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	if(success)
		NSLog(@"No Errors");
	else
		NSLog(@"Error Error Error!!!");
	[pool release];
}

- (void)applicationWillTerminate:(UIApplication *)application {
	// Save data if appropriate
}
- (void)addToItemList:(eBayItem *)newItem
{
    [self.list addObject:newItem];
    // The XML parser calls addToEarthquakeList: each time it creates an earthquake object.
    // The table needs to be reloaded to reflect the new content of the list.
    [self reloadTable];
}
- (void)reloadTable
{
	//NSLog(@"Reload Data");
    [[(RootViewController *)[self.navigationController topViewController] tableView] reloadData];
	//[[(RootViewController *)[self.navigationController topViewController] tableView] setNeedsDisplay];
}
- (void)dealloc {
	[list release];
	[navigationController release];
	[window release];
	[super dealloc];
}

@end
